package me.seu.demo.service.wechat;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.service.wechat.message.FileMessage;
import me.seu.demo.service.wechat.model.MaterialFileVo;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 获取上传素材响应信息
 *
 * @author liangfeihu
 * @since 2021/10/19 16:53
 */
@Slf4j
public class GetTencentMaterialFileUtils {

    private static String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=file";

    /**
     * 从腾讯获取上传素材
     *
     * @param filePath
     * @param webHookKey
     * @return
     */
    public static String getMediaId(String filePath, String webHookKey) {

        if (StringUtils.isAnyEmpty(filePath, webHookKey)) {
            return StringUtils.EMPTY;
        }
        try {
            File file = new File(filePath);
            byte[] bytesArray = new byte[(int) file.length()];
            FileInputStream fis = new FileInputStream(file);
            // read file into bytes[]
            fis.read(bytesArray);
            fis.close();
            HttpResponse response = HttpRequest.post(String.format(url, webHookKey))
                    .header("multipart/form-data", "multipart/form-data")
                    .header("Content-Disposition", String.format("form-data; name=\"media\";filename=\"%s\"; filelength=%s", file.getName(), file.length()))
                    .header("Content-Type", "application/octet-stream")
                    .form("key", bytesArray, file.getName())
                    .execute();

            final MaterialFileVo materialFileVo = JSONUtil.toBean(response.body(), MaterialFileVo.class);
            if (null == materialFileVo || materialFileVo.getErrcode() != 0) {
                return StringUtils.EMPTY;
            }
            return materialFileVo.getMediaId();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("GetTencentMaterialFileUtils getMediaId IOException {}", e.getMessage());
        }
        return null;
    }


    public static void main(String[] args) {
        // 机器人对应key
        String webhook = "e931426f-75a8-4c05-822a-26598ffb7609";

        final String mediaId = getMediaId("/Users/a123/codes/myown/learning-demo/common-demo/src/main/resources/img/zhuyin.jpg", webhook);
        if (StringUtils.isEmpty(mediaId)) {
            return;
        }

        FileMessage fileMessage = new FileMessage(mediaId);
        WxChatRobotClient.send(webhook, fileMessage);
    }

}
